package eolympics.server;

import jexxus.server.ConnectionToClient;

import com.google.common.base.Preconditions;

import data.GameState;
import data.Player;
import eolympics.Communicator;

class GameServerWaitingForStartState
        extends GameServerParentState
{
    public GameServerWaitingForStartState(IGameServer pGameServer)
    {
        super(pGameServer);
    }

    @Override
    public void clientConnected( final ConnectionToClient pNewClient )
    {
        if( mGameData.getNumberOfPlayers() == GameServer.MAXIMUM_NUMBER_OF_PLAYERS )
        {
            pNewClient.close();
            return;
        }

        Communicator.sendGameStateToClient(getGameState(), pNewClient);
    }

    @Override
    public void playerWantsToJoin( final Player pPlayerAskingToJoin )
    {
        addNewPlayerWithValidetNameAndInformClients(pPlayerAskingToJoin);
    }

    @Override
    public void playerIsReady( final Player pPlayerWhoIsReady )
    {
        boolean allPlayersReady = setPlayerReadyAndCheckIfAllPlayersAreReady(pPlayerWhoIsReady);

        if( allPlayersReady )
        {
            GameServerWaitingForStartOfMiniGameState nextState = new GameServerWaitingForStartOfMiniGameState(mGameServer);
            mGameServer.changeGameState(nextState);
        }
        else
        {
            mGameServer.sendPlayerListChangedToClients();
        }
    }

    @Override
    public GameState getGameState()
    {
        return GameState.WAITING_FOR_START;
    }

    @Override
    public void addAiPlayer( final Player pAiPlayer )
    {
        if( mGameData.getNumberOfPlayers() == GameServer.MAXIMUM_NUMBER_OF_PLAYERS )
        {
            return;
        }

        Preconditions.checkNotNull(pAiPlayer);

        pAiPlayer.setReady(true);
        addNewPlayerWithValidetNameAndInformClients(pAiPlayer);
    }

    @Override
    public void removeAiPlayer( final String pAiPlayerName )
    {
        Player aiPlayer = mGameData.getPlayerForName(pAiPlayerName);

        if( aiPlayer == null )
        {
            return;
        }
        if( !aiPlayer.isAiPlayer() )
        {
            return;
        }

        mGameData.removePlayer(aiPlayer);

        mGameServer.sendPlayerListChangedToClients();
    }
}
